package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    //根据id，查询字典子数据
    @Override
    @Cacheable(value = "aaa",keyGenerator = "keyGenerator")
    public List<Dict> findChirdData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        //向dictList中设置hasChildren属性
        for (Dict dict : dictList) {
            Long dictId = dict.getId();
            boolean isChild = hasChildren(dictId);
            dict.setHasChildren(isChild);
        }
        return dictList;
    }
    //判断id下面是否有子节点
    public boolean hasChildren(Long id){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);

        //count=0时，为false；count>0时，为true
        return count>0;
    }

    //下载数据字典
    @Override
    public void downloadDict(HttpServletResponse response)  {
        //设置response信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = null;
        try {
            fileName = URLEncoder.encode("数据字典","utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");

        //查询数据库获取字典全部数据
        List<Dict> dictList = baseMapper.selectList(null);
        List<DictEeVo> dictEeVoList = new ArrayList<>();
        //Dict --> DictEeVo
        for (Dict dict : dictList) {
            DictEeVo dictEeVO = new DictEeVo();
            BeanUtils.copyProperties(dict,dictEeVO);  //复制属性,相同名字的属性复制
            dictEeVoList.add(dictEeVO);
        }

        //excel导出
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet().doWrite(dictEeVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //上传数据字典
    @Override
    @CacheEvict(value = "aaa",allEntries = true)
    public void importDict(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取字典名称
    @Override
    public String getDictName(String dictCode, String value) {
        //根据双条件，联合查询
        //如果dictCode为空，则根据value做查询
        if (StringUtils.isEmpty(dictCode)){
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("value", value));
            return dict.getName();
        }
        //如果不为空，则根据dictCode查询出对象，得到id
        Long id = this.getDictByDictcode(dictCode).getId();
        //逻辑：根据查询的id，如果等同于parent_id列的值，得到若干个对象，再根据value，就能判断是具体的对象
        Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("parent_id", id).eq("value", value));
        return dict.getName();
    }

    //根据dictcode获取Dict对象
    public Dict getDictByDictcode(String Dictcode){
        return baseMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", Dictcode));
    }

    //根据dictCode获取下级节点
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //获取Dict对象
        Dict dict = this.getDictByDictcode(dictCode);
        //获取id获取子节点
        List<Dict> chirdData = this.findChirdData(dict.getId());
        return chirdData;
    }




}

